import {Component} from '@angular/core';
import {Observable} from "rxjs";
import {AuthService} from "./core/auth.service";
import {Router} from "@angular/router";
import {environment} from "../environments/environment";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  isAuthenticated$: Observable<boolean>;
  isDoneLoading$: Observable<boolean>;
  canActivateProtectedRoutes$: Observable<boolean>;

  constructor(private authService: AuthService, private router: Router,) {
    this.isAuthenticated$ = authService.isAuthenticated$;
    this.isDoneLoading$ = this.authService.isDoneLoading$;
    this.canActivateProtectedRoutes$ = this.authService.canActivateProtectedRoutes$;
  }

  login() { this.authService.login(); }
  logout() { this.authService.logout();  }
  refresh() { this.authService.refresh(); }  //静默刷新
  reload() { window.location.reload(); }
  clearStorage() { localStorage.clear(); }

  logoutExternally() { window.open(this.authService.logoutUrl); }

  get email(): string {
    return this.authService.identityClaims
      ? (this.authService.identityClaims as any)['email']
      : '-';
  }
  get hasValidToken() { return this.authService.hasValidToken(); }
  get accessToken() { return this.authService.accessToken; }
  get refreshToken() { return this.authService.refreshToken; }
  get identityClaims() { return this.authService.identityClaims; }
  get idToken() { return this.authService.idToken; }

  sso() {
    const redirectUri = "http://localhost:4200/login"
    const clientId = 'client'
    const state = this.router.url
    const parameter = `response_type=code&redirect_uri=${redirectUri}&client_id=${clientId}&state=${state}`;
    window.location.href = `${environment.oauthUrl}/oauth/authorize?${parameter}`
  }

  // 侧边栏折叠
  isCollapsed = false;
}
